import { Schema, model, Types } from "mongoose";

export interface Placement {
  imageId: Types.ObjectId;
  x: number;
  y: number;
  width: number;
  height: number;
  rotation?: number;
  zIndex?: number;
  opacity?: number;
}

export interface CompositionDoc {
  _id: Types.ObjectId;
  name: string;
  width: number;
  height: number;
  background?: string;
  placements: Placement[];
  createdAt: Date;
  updatedAt: Date;
}

const PlacementSchema = new Schema<Placement>(
  {
    imageId: { type: Schema.Types.ObjectId, ref: "Image", required: true },
    x: { type: Number, required: true },
    y: { type: Number, required: true },
    width: { type: Number, required: true },
    height: { type: Number, required: true },
    rotation: { type: Number, default: 0 },
    zIndex: { type: Number, default: 0 },
    opacity: { type: Number, default: 1 },
  },
  { _id: false }
);

const CompositionSchema = new Schema<CompositionDoc>(
  {
    name: { type: String, required: true },
    width: { type: Number, required: true },
    height: { type: Number, required: true },
    background: { type: String },
    placements: { type: [PlacementSchema], default: [] },
  },
  { timestamps: true }
);

CompositionSchema.index({ createdAt: -1 });

export const CompositionModel = model<CompositionDoc>(
  "Composition",
  CompositionSchema
);
